<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Si24R1无人机通信模拟演示</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36BFFA',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        dark: '#1D2129',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
            .card-hover {
                @apply hover:shadow-lg hover:-translate-y-1 transition-all duration-300;
            }
            .status-indicator {
                @apply w-3 h-3 rounded-full inline-block;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-md fixed w-full top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-cubes text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">Si24R1 无线通信模拟</h1>
            </div>
            <div class="flex items-center space-x-4">
                <span id="connection-status" class="hidden md:inline-flex items-center text-sm">
                    <span class="status-indicator bg-danger mr-2"></span>
                    <span>未连接</span>
                </span>
                <button id="reset-btn" class="bg-gray-200 hover:bg-gray-300 text-dark px-3 py-1 rounded text-sm flex items-center">
                    <i class="fa fa-refresh mr-1"></i> 重置
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-20 pb-16">
        <!-- 状态概览 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow p-5 card-hover">
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="text-gray-500 text-sm font-medium">模块状态</h3>
                        <p id="module-status" class="text-2xl font-bold mt-1">未初始化</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                        <i class="fa fa-wifi text-primary"></i>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-gray-100">
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-500">模式:</span>
                        <span id="current-mode" class="font-medium">未设置</span>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow p-5 card-hover">
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="text-gray-500 text-sm font-medium">通信统计</h3>
                        <p class="text-2xl font-bold mt-1">0 次传输</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                        <i class="fa fa-exchange text-secondary"></i>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-gray-100 grid grid-cols-2 gap-2">
                    <div class="text-sm">
                        <span class="text-gray-500">发送成功:</span>
                        <span id="tx-success" class="font-medium text-success">0</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">接收成功:</span>
                        <span id="rx-success" class="font-medium text-success">0</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">发送失败:</span>
                        <span id="tx-fail" class="font-medium text-danger">0</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">信号强度:</span>
                        <span id="signal-strength" class="font-medium">-</span>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow p-5 card-hover">
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="text-gray-500 text-sm font-medium">无人机状态</h3>
                        <p id="drone-status" class="text-2xl font-bold mt-1">未启动</p>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                        <i class="fa fa-plane text-primary"></i>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-gray-100 grid grid-cols-2 gap-2">
                    <div class="text-sm">
                        <span class="text-gray-500">高度:</span>
                        <span id="drone-height" class="font-medium">0m</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">电池:</span>
                        <span id="drone-battery" class="font-medium">100%</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">速度:</span>
                        <span id="drone-speed" class="font-medium">0km/h</span>
                    </div>
                    <div class="text-sm">
                        <span class="text-gray-500">指令:</span>
                        <span id="last-command" class="font-medium">无</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 模拟区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- 左侧：无人机 -->
            <div class="bg-white rounded-xl shadow p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-plane text-primary mr-2"></i>无人机 (接收端)
                </h2>
                
                <div class="flex justify-center mb-6">
                    <div id="drone-visual" class="w-40 h-40 relative">
                        <img src="https://picsum.photos/seed/drone/200/200" alt="无人机图示" class="w-full h-full object-contain opacity-50 transition-all-300">
                        <div id="drone-status-overlay" class="absolute inset-0 flex items-center justify-center bg-black/30 rounded-full opacity-0 transition-all-300">
                            <span class="text-white font-bold">未启动</span>
                        </div>
                    </div>
                </div>
                
                <div class="space-y-3">
                    <div>
                        <h3 class="text-sm font-medium text-gray-500 mb-1">接收缓冲区</h3>
                        <div id="rx-buffer" class="bg-gray-50 p-3 rounded text-sm font-mono h-24 overflow-y-auto">
                            等待接收数据...
                        </div>
                    </div>
                    
                    <div class="pt-3">
                        <button id="init-rx-btn" class="w-full bg-primary hover:bg-primary/90 text-white py-2 rounded transition-all-300 flex items-center justify-center">
                            <i class="fa fa-play mr-2"></i>初始化接收模式
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 中间：通信流程 -->
            <div class="bg-white rounded-xl shadow p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-code-fork text-primary mr-2"></i>通信流程演示
                </h2>
                
                <div id="communication-log" class="bg-gray-50 p-4 rounded-lg h-64 overflow-y-auto text-sm mb-4 space-y-2">
                    <div class="text-gray-500 italic">通信日志将显示在这里...</div>
                </div>
                
                <div class="grid grid-cols-2 gap-3">
                    <button id="start-communication" class="bg-success hover:bg-success/90 text-white py-2 rounded transition-all-300 flex items-center justify-center">
                        <i class="fa fa-play mr-1"></i> 开始通信
                    </button>
                    <button id="stop-communication" class="bg-danger hover:bg-danger/90 text-white py-2 rounded transition-all-300 flex items-center justify-center" disabled>
                        <i class="fa fa-stop mr-1"></i> 停止通信
                    </button>
                </div>
            </div>
            
            <!-- 右侧：手柄控制器 -->
            <div class="bg-white rounded-xl shadow p-5">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-gamepad text-primary mr-2"></i>手柄控制器 (发送端)
                </h2>
                
                <div class="flex justify-center mb-6">
                    <div id="controller-visual" class="w-40 h-40 relative">
                        <img src="https://picsum.photos/seed/controller/200/200" alt="手柄图示" class="w-full h-full object-contain opacity-50 transition-all-300">
                    </div>
                </div>
                
                <div class="space-y-3">
                    <div>
                        <h3 class="text-sm font-medium text-gray-500 mb-1">发送缓冲区</h3>
                        <div id="tx-buffer" class="bg-gray-50 p-3 rounded text-sm font-mono h-24 overflow-y-auto">
                            等待输入指令...
                        </div>
                    </div>
                    
                    <div class="pt-3 grid grid-cols-2 gap-2">
                        <button id="init-tx-btn" class="bg-primary hover:bg-primary/90 text-white py-2 rounded transition-all-300 flex items-center justify-center">
                            <i class="fa fa-play mr-2"></i>初始化发送模式
                        </button>
                        <button id="send-command-btn" class="bg-secondary hover:bg-secondary/90 text-white py-2 rounded transition-all-300 flex items-center justify-center" disabled>
                            <i class="fa fa-paper-plane mr-1"></i> 发送指令
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 代码调用演示 -->
        <div class="bg-white rounded-xl shadow p-5 mb-8">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-code text-primary mr-2"></i>代码调用演示
            </h2>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider rounded-tl-lg">操作</th>
                            <th class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">函数调用</th>
                            <th class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider rounded-tr-lg">结果</th>
                        </tr>
                    </thead>
                    <tbody id="function-calls" class="bg-white divide-y divide-gray-200">
                        <tr class="hover:bg-gray-50">
                            <td colspan="4" class="px-4 py-4 text-center text-gray-500 italic">等待操作开始...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 指令面板 -->
        <div class="bg-white rounded-xl shadow p-5">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fa fa-list-ul text-primary mr-2"></i>无人机控制指令
            </h2>
            
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="takeoff">
                    <i class="fa fa-rocket text-xl mb-1"></i>
                    <span class="text-sm">起飞</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="land">
                    <i class="fa fa-moon-o text-xl mb-1"></i>
                    <span class="text-sm">降落</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="up">
                    <i class="fa fa-arrow-up text-xl mb-1"></i>
                    <span class="text-sm">上升</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="down">
                    <i class="fa fa-arrow-down text-xl mb-1"></i>
                    <span class="text-sm">下降</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="forward">
                    <i class="fa fa-arrow-forward text-xl mb-1"></i>
                    <span class="text-sm">前进</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="backward">
                    <i class="fa fa-arrow-back text-xl mb-1"></i>
                    <span class="text-sm">后退</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="left">
                    <i class="fa fa-arrow-left text-xl mb-1"></i>
                    <span class="text-sm">左移</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="right">
                    <i class="fa fa-arrow-right text-xl mb-1"></i>
                    <span class="text-sm">右移</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="rotateleft">
                    <i class="fa fa-rotate-left text-xl mb-1"></i>
                    <span class="text-sm">左转</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="rotateright">
                    <i class="fa fa-rotate-right text-xl mb-1"></i>
                    <span class="text-sm">右转</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="hover">
                    <i class="fa fa-pause text-xl mb-1"></i>
                    <span class="text-sm">悬停</span>
                </button>
                <button class="command-btn bg-gray-100 hover:bg-gray-200 py-3 rounded transition-all-300 flex flex-col items-center justify-center" data-command="emergencystop">
                    <i class="fa fa-exclamation-triangle text-xl mb-1 text-danger"></i>
                    <span class="text-sm">紧急停止</span>
                </button>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-6">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm text-gray-400">© 2023 Si24R1 无线通信模拟演示</p>
                </div>
                <div class="flex space-x-4">
                    <a href="#" class="text-gray-400 hover:text-white transition-all-300">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-gray-400 hover:text-white transition-all-300">
                        <i class="fa fa-info-circle text-xl"></i>
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 全局状态变量
        const state = {
            txInitialized: false,
            rxInitialized: false,
            communicationActive: false,
            txCount: 0,
            rxCount: 0,
            txFailCount: 0,
            droneState: '未启动',
            currentCommand: '无',
            autoSendInterval: null,
            signalStrength: 0
        };

        // DOM 元素引用
        const elements = {
            moduleStatus: document.getElementById('module-status'),
            currentMode: document.getElementById('current-mode'),
            txSuccess: document.getElementById('tx-success'),
            rxSuccess: document.getElementById('rx-success'),
            txFail: document.getElementById('tx-fail'),
            signalStrength: document.getElementById('signal-strength'),
            droneStatus: document.getElementById('drone-status'),
            droneHeight: document.getElementById('drone-height'),
            droneBattery: document.getElementById('drone-battery'),
            droneSpeed: document.getElementById('drone-speed'),
            lastCommand: document.getElementById('last-command'),
            rxBuffer: document.getElementById('rx-buffer'),
            txBuffer: document.getElementById('tx-buffer'),
            communicationLog: document.getElementById('communication-log'),
            functionCalls: document.getElementById('function-calls'),
            connectionStatus: document.getElementById('connection-status'),
            droneVisual: document.querySelector('#drone-visual img'),
            droneStatusOverlay: document.getElementById('drone-status-overlay'),
            controllerVisual: document.querySelector('#controller-visual img'),
            
            // 按钮
            initRxBtn: document.getElementById('init-rx-btn'),
            initTxBtn: document.getElementById('init-tx-btn'),
            sendCommandBtn: document.getElementById('send-command-btn'),
            startCommunication: document.getElementById('start-communication'),
            stopCommunication: document.getElementById('stop-communication'),
            resetBtn: document.getElementById('reset-btn'),
            commandBtns: document.querySelectorAll('.command-btn')
        };

        // 指令映射表
        const commandMap = {
            'takeoff': { code: 0x01, desc: '起飞' },
            'land': { code: 0x02, desc: '降落' },
            'up': { code: 0x03, desc: '上升' },
            'down': { code: 0x04, desc: '下降' },
            'forward': { code: 0x05, desc: '前进' },
            'backward': { code: 0x06, desc: '后退' },
            'left': { code: 0x07, desc: '左移' },
            'right': { code: 0x08, desc: '右移' },
            'rotateleft': { code: 0x09, desc: '左转' },
            'rotateright': { code: 0x0A, desc: '右转' },
            'hover': { code: 0x0B, desc: '悬停' },
            'emergencystop': { code: 0xFF, desc: '紧急停止' }
        };

        // 初始化接收模式
        function initRxMode() {
            if (state.rxInitialized) return;
            
            addLog('无人机: 开始初始化接收模式...');
            addFunctionCall('初始化接收模式', 'Inf_Si24R1_RXMode()', '执行中');
            
            // 模拟初始化过程
            setTimeout(() => {
                state.rxInitialized = true;
                elements.moduleStatus.textContent = '已初始化';
                elements.currentMode.textContent = '接收模式 (无人机)';
                elements.droneVisual.classList.remove('opacity-50');
                elements.droneVisual.classList.add('opacity-100');
                
                // 执行自检
                addFunctionCall('模块自检', 'Inf_Si24R1_Check()', '执行中');
                setTimeout(() => {
                    addFunctionCall('模块自检', 'Inf_Si24R1_Check()', '完成', '成功');
                    addLog('无人机: 接收模式初始化完成，等待接收数据...');
                    
                    // 更新连接状态
                    updateConnectionStatus();
                }, 800);
            }, 1200);
            
            elements.initRxBtn.disabled = true;
            elements.initRxBtn.classList.remove('bg-primary', 'hover:bg-primary/90');
            elements.initRxBtn.classList.add('bg-gray-400', 'cursor-not-allowed');
        }

        // 初始化发送模式
        function initTxMode() {
            if (state.txInitialized) return;
            
            addLog('手柄: 开始初始化发送模式...');
            addFunctionCall('初始化发送模式', 'Inf_Si24R1_TXMode()', '执行中');
            
            // 模拟初始化过程
            setTimeout(() => {
                state.txInitialized = true;
                elements.moduleStatus.textContent = '已初始化';
                elements.currentMode.textContent = '发送模式 (手柄)';
                elements.controllerVisual.classList.remove('opacity-50');
                elements.controllerVisual.classList.add('opacity-100');
                
                // 执行自检
                addFunctionCall('模块自检', 'Inf_Si24R1_Check()', '执行中');
                setTimeout(() => {
                    addFunctionCall('模块自检', 'Inf_Si24R1_Check()', '完成', '成功');
                    addLog('手柄: 发送模式初始化完成，准备发送数据...');
                    
                    // 启用发送按钮
                    elements.sendCommandBtn.disabled = false;
                    
                    // 更新连接状态
                    updateConnectionStatus();
                }, 800);
            }, 1200);
            
            elements.initTxBtn.disabled = true;
            elements.initTxBtn.classList.remove('bg-primary', 'hover:bg-primary/90');
            elements.initTxBtn.classList.add('bg-gray-400', 'cursor-not-allowed');
        }

        // 发送指令
        function sendCommand(command) {
            if (!state.txInitialized || !state.rxInitialized) {
                addLog('错误: 请先初始化发送端和接收端!', 'error');
                return;
            }
            
            const cmd = commandMap[command];
            if (!cmd) return;
            
            // 更新发送缓冲区
            elements.txBuffer.innerHTML = `发送指令: ${cmd.desc} (0x${cmd.code.toString(16).toUpperCase()})`;
            
            // 记录函数调用
            addLog(`手柄: 发送指令 - ${cmd.desc}`);
            addFunctionCall('发送数据包', `Inf_Si24R1_TxPacket(0x${cmd.code.toString(16)})`, '执行中');
            
            // 模拟发送过程
            setTimeout(() => {
                // 模拟信号强度变化
                state.signalStrength = Math.floor(Math.random() * 30) + 70;
                elements.signalStrength.textContent = `${state.signalStrength}%`;
                
                // 模拟发送结果（95%成功率）
                const success = Math.random() > 0.05;
                
                if (success) {
                    state.txCount++;
                    elements.txSuccess.textContent = state.txCount;
                    addFunctionCall('发送数据包', `Inf_Si24R1_TxPacket(0x${cmd.code.toString(16)})`, '完成', '成功');
                    
                    // 接收端处理
                    receiveCommand(command);
                } else {
                    state.txFailCount++;
                    elements.txFail.textContent = state.txFailCount;
                    addFunctionCall('发送数据包', `Inf_Si24R1_TxPacket(0x${cmd.code.toString(16)})`, '完成', '失败 (重发上限)');
                    addLog(`手柄: 发送失败 - 未收到确认信号`, 'error');
                }
            }, 800);
        }

        // 接收指令
        function receiveCommand(command) {
            const cmd = commandMap[command];
            if (!cmd) return;
            
            // 记录函数调用
            addFunctionCall('接收数据包', 'Inf_Si24R1_RxPacket(RX_BUFF)', '执行中');
            
            // 模拟接收过程
            setTimeout(() => {
                state.rxCount++;
                elements.rxSuccess.textContent = state.rxCount;
                addFunctionCall('接收数据包', 'Inf_Si24R1_RxPacket(RX_BUFF)', '完成', '成功');
                
                // 更新接收缓冲区
                elements.rxBuffer.innerHTML = `接收指令: ${cmd.desc} (0x${cmd.code.toString(16).toUpperCase()})`;
                addLog(`无人机: 接收到指令 - ${cmd.desc}`);
                
                // 更新无人机状态
                updateDroneState(command);
            }, 500);
        }

        // 更新无人机状态
        function updateDroneState(command) {
            const cmd = commandMap[command];
            state.currentCommand = cmd.desc;
            elements.lastCommand.textContent = cmd.desc;
            
            switch(command) {
                case 'takeoff':
                    state.droneState = '飞行中';
                    elements.droneStatus.textContent = '飞行中';
                    elements.droneHeight.textContent = '10m';
                    elements.droneSpeed.textContent = '0km/h';
                    elements.droneStatusOverlay.innerHTML = '<span class="text-white font-bold">飞行中</span>';
                    elements.droneStatusOverlay.classList.remove('bg-black/30', 'opacity-0');
                    elements.droneStatusOverlay.classList.add('bg-success/30', 'opacity-100');
                    break;
                case 'land':
                    state.droneState = '已降落';
                    elements.droneStatus.textContent = '已降落';
                    elements.droneHeight.textContent = '0m';
                    elements.droneSpeed.textContent = '0km/h';
                    elements.droneStatusOverlay.innerHTML = '<span class="text-white font-bold">已降落</span>';
                    elements.droneStatusOverlay.classList.remove('bg-success/30');
                    elements.droneStatusOverlay.classList.add('bg-blue-500/30');
                    break;
                case 'up':
                    const currentHeight = parseInt(elements.droneHeight.textContent);
                    elements.droneHeight.textContent = `${currentHeight + 5}m`;
                    break;
                case 'down':
                    const currentH = parseInt(elements.droneHeight.textContent);
                    elements.droneHeight.textContent = `${Math.max(0, currentH - 5)}m`;
                    break;
                case 'forward':
                case 'backward':
                case 'left':
                case 'right':
                    elements.droneSpeed.textContent = '5km/h';
                    // 3秒后恢复悬停状态
                    setTimeout(() => {
                        if (state.droneState === '飞行中') {
                            elements.droneSpeed.textContent = '0km/h';
                        }
                    }, 3000);
                    break;
                case 'emergencystop':
                    state.droneState = '紧急停止';
                    elements.droneStatus.textContent = '紧急停止';
                    elements.droneHeight.textContent = '0m';
                    elements.droneSpeed.textContent = '0km/h';
                    elements.droneStatusOverlay.innerHTML = '<span class="text-white font-bold">紧急停止</span>';
                    elements.droneStatusOverlay.classList.remove('bg-success/30', 'bg-blue-500/30');
                    elements.droneStatusOverlay.classList.add('bg-danger/30');
                    break;
            }
            
            // 模拟电池消耗
            const currentBattery = parseInt(elements.droneBattery.textContent);
            if (currentBattery > 0) {
                elements.droneBattery.textContent = `${Math.max(0, currentBattery - 1)}%`;
            }
        }

        // 开始自动通信
        function startAutoCommunication() {
            if (state.communicationActive || !state.txInitialized || !state.rxInitialized) return;
            
            state.communicationActive = true;
            elements.startCommunication.disabled = true;
            elements.stopCommunication.disabled = false;
            
            addLog('开始自动发送控制指令...');
            
            // 每2秒发送一个随机指令
            state.autoSendInterval = setInterval(() => {
                const commands = Object.keys(commandMap);
                // 排除紧急停止和起飞/降落，避免冲突
                const safeCommands = commands.filter(cmd => 
                    cmd !== 'emergencystop' && 
                    cmd !== 'takeoff' && 
                    cmd !== 'land'
                );
                const randomCmd = safeCommands[Math.floor(Math.random() * safeCommands.length)];
                sendCommand(randomCmd);
            }, 2000);
        }

        // 停止自动通信
        function stopAutoCommunication() {
            if (!state.communicationActive) return;
            
            clearInterval(state.autoSendInterval);
            state.communicationActive = false;
            elements.startCommunication.disabled = false;
            elements.stopCommunication.disabled = true;
            
            addLog('已停止自动发送控制指令');
        }

        // 重置所有状态
        function resetAll() {
            stopAutoCommunication();
            
            // 重置状态变量
            state.txInitialized = false;
            state.rxInitialized = false;
            state.communicationActive = false;
            state.txCount = 0;
            state.rxCount = 0;
            state.txFailCount = 0;
            state.droneState = '未启动';
            state.currentCommand = '无';
            state.signalStrength = 0;
            
            // 重置UI
            elements.moduleStatus.textContent = '未初始化';
            elements.currentMode.textContent = '未设置';
            elements.txSuccess.textContent = '0';
            elements.rxSuccess.textContent = '0';
            elements.txFail.textContent = '0';
            elements.signalStrength.textContent = '-';
            elements.droneStatus.textContent = '未启动';
            elements.droneHeight.textContent = '0m';
            elements.droneBattery.textContent = '100%';
            elements.droneSpeed.textContent = '0km/h';
            elements.lastCommand.textContent = '无';
            elements.rxBuffer.innerHTML = '等待接收数据...';
            elements.txBuffer.innerHTML = '等待输入指令...';
            elements.droneVisual.classList.remove('opacity-100');
            elements.droneVisual.classList.add('opacity-50');
            elements.controllerVisual.classList.remove('opacity-100');
            elements.controllerVisual.classList.add('opacity-50');
            elements.droneStatusOverlay.classList.remove('bg-success/30', 'bg-blue-500/30', 'bg-danger/30', 'opacity-100');
            elements.droneStatusOverlay.classList.add('bg-black/30', 'opacity-0');
            elements.droneStatusOverlay.innerHTML = '<span class="text-white font-bold">未启动</span>';
            
            // 重置按钮状态
            elements.initRxBtn.disabled = false;
            elements.initRxBtn.classList.remove('bg-gray-400', 'cursor-not-allowed');
            elements.initRxBtn.classList.add('bg-primary', 'hover:bg-primary/90');
            
            elements.initTxBtn.disabled = false;
            elements.initTxBtn.classList.remove('bg-gray-400', 'cursor-not-allowed');
            elements.initTxBtn.classList.add('bg-primary', 'hover:bg-primary/90');
            
            elements.sendCommandBtn.disabled = true;
            elements.startCommunication.disabled = false;
            elements.stopCommunication.disabled = true;
            
            // 清空日志
            elements.communicationLog.innerHTML = '<div class="text-gray-500 italic">通信日志将显示在这里...</div>';
            elements.functionCalls.innerHTML = '<tr class="hover:bg-gray-50"><td colspan="4" class="px-4 py-4 text-center text-gray-500 italic">等待操作开始...</td></tr>';
            
            // 更新连接状态
            updateConnectionStatus();
            
            addLog('已重置所有状态');
        }

        // 添加日志
        function addLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            
            logEntry.className = type === 'error' ? 'text-danger' : '';
            logEntry.innerHTML = `[${timestamp}] ${message}`;
            
            // 如果是第一个条目，先清空
            if (elements.communicationLog.querySelector('.italic')) {
                elements.communicationLog.innerHTML = '';
            }
            
            elements.communicationLog.appendChild(logEntry);
            elements.communicationLog.scrollTop = elements.communicationLog.scrollHeight;
        }

        // 添加函数调用记录
        function addFunctionCall(operation, functionName, status, result = '-') {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50';
            
            // 状态样式
            let statusClass = '';
            if (status === '执行中') statusClass = 'text-warning';
            else if (status === '完成' && result === '成功') statusClass = 'text-success';
            else if (status === '完成' && result === '失败') statusClass = 'text-danger';
            
            // 结果样式
            let resultClass = '';
            if (result === '成功') resultClass = 'text-success';
            else if (result === '失败') resultClass = 'text-danger';
            
            row.innerHTML = `
                <td class="px-4 py-3 whitespace-nowrap">${operation}</td>
                <td class="px-4 py-3 font-mono text-sm">${functionName}</td>
                <td class="px-4 py-3 whitespace-nowrap"><span class="${statusClass}">${status}</span></td>
                <td class="px-4 py-3 whitespace-nowrap"><span class="${resultClass}">${result}</span></td>
            `;
            
            // 如果是第一个条目，先清空
            if (elements.functionCalls.querySelector('td[colspan="4"]')) {
                elements.functionCalls.innerHTML = '';
            }
            
            elements.functionCalls.appendChild(row);
            elements.functionCalls.scrollTop = elements.functionCalls.scrollHeight;
        }

        // 更新连接状态
        function updateConnectionStatus() {
            const statusIndicator = elements.connectionStatus.querySelector('.status-indicator');
            const statusText = elements.connectionStatus.querySelector('span:last-child');
            
            if (state.txInitialized && state.rxInitialized) {
                statusIndicator.className = 'status-indicator bg-success mr-2';
                statusText.textContent = '已连接';
                addLog('发送端和接收端已成功连接');
            } else if (state.txInitialized || state.rxInitialized) {
                statusIndicator.className = 'status-indicator bg-warning mr-2';
                statusText.textContent = '部分连接';
            } else {
                statusIndicator.className = 'status-indicator bg-danger mr-2';
                statusText.textContent = '未连接';
            }
        }

        // 事件监听
        elements.initRxBtn.addEventListener('click', initRxMode);
        elements.initTxBtn.addEventListener('click', initTxMode);
        elements.sendCommandBtn.addEventListener('click', () => {
            // 默认发送悬停指令
            sendCommand('hover');
        });
        elements.startCommunication.addEventListener('click', startAutoCommunication);
        elements.stopCommunication.addEventListener('click', stopAutoCommunication);
        elements.resetBtn.addEventListener('click', resetAll);
        
        // 指令按钮事件
        elements.commandBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const command = btn.getAttribute('data-command');
                sendCommand(command);
            });
        });

        // 初始化页面
        updateConnectionStatus();
    </script>
</body>
</html>
